import { _decorator, Component, Node, Label, ButtonComponent, director, find } from 'cc';
import { Constants } from "../data/Constants";
import { UIManager } from "../utils/UIManager";
import { TopicManger } from "./TopicManger";
import { onShareAppMessage } from "../utils/shareMgr";
import useStore from "../store";
import api from '../api'

const { ccclass, property } = _decorator;

@ccclass('overGame')
export class overGame extends Component {
  @property({ type: Node })
  public shareRef: Node | null = null; // 分享

  @property({ type: Node })
  public afreshBoxRef: Node | null = null; // 重新开始

  @property({ type: Node })
  public videoBoxRef: Node | null = null; // 看视频

  @property({ type: Node })
  public continueBoxRef: Node | null = null; // 继续

  @property({ type: Node })
  public shareBtn: Node | null = null; // 分享BTN

  @property({ type: Node })
  public shareSkipBtn: Node | null = null; // 分享跳过

  @property({ type: Node })
  public videoBtn: Node | null = null; // 看视频BTN

  @property({ type: Node })
  public videoSkipBtn: Node | null = null; // 看视频跳过

  @property({ type: Node })
  public afreshBtn: Node | null = null; // 重新开始BTN

  @property({ type: Node })
  public afreshShareBtn: Node | null = null; // 重新开始分享BTN

  @property({ type: Node })
  public afreshHomeBtn: Node | null = null; // 重新开始返回首页BTN

  @property({ type: Node })
  public continueBtn: Node | null = null; // 继续开始BTN


  public static LayoutRef : Node = null
  public static isShowAd = false // 是否看过视频
  public static isAdEnded = false // 视频是否可以展示
  public static isRevive = false // 是否复活过
  public static isNewMaxScore = false // 是否需要更新分数
  public static isStart = true

  private videoAd = null
  private showADCount = 0

  onEnable() {
    console.log(this, 'onEnable')
    if (!overGame.isStart) {
      this.handleRefShow()
    }
  }

  start() {
    console.log('overGame-start')
    this.init()
  }

  init() {
    overGame.LayoutRef = find("Canvas/over-modal-dialog/content/game-over/Layout")
    
    this.shareBtn.on(Node.EventType.TOUCH_START, this.handleShare, this);
    this.shareSkipBtn.on(Node.EventType.TOUCH_START, this.handleSkip, this);

    this.videoBtn.on(Node.EventType.TOUCH_START, this.watchVideo, this);
    this.videoSkipBtn.on(Node.EventType.TOUCH_START, this.handleSkip, this);

    this.afreshBtn.on(Node.EventType.TOUCH_START, this.restart, this);
    this.afreshShareBtn.on(Node.EventType.TOUCH_START, this.afreshShare, this);
    this.afreshHomeBtn.on(Node.EventType.TOUCH_START, this.backHome, this);

    this.continueBtn.on(Node.EventType.TOUCH_START, this.continueGame, this);

    overGame.isStart = false
    this.createVideoAd() // 请求视频
    console.log('初始化init')
    this.handleRefShow()
  }

  // 初始化展示哪个nodeRef
  handleRefShow() {
    console.log('展示哪个nodeRef')
    this.updataScore()
    if (overGame.isRevive) { // 复活过只能展示重新开始
      return this.afreshBoxRefShow()
    }

    if (!TopicManger.isShare && typeof wx !== 'undefined') { // 展示分享
      this.shareRefShow()
    } else if (!overGame.isShowAd && overGame.isAdEnded) {
      this.videoBoxRefShow()
    } else {
      this.afreshBoxRefShow()
    }
  }

  updataScore () {
    const maxScore = Number(TopicManger.curScore) > Number(useStore().userStore.userInfo.maxScore) ? TopicManger.curScore : Number(useStore().userStore.userInfo.maxScore)
    overGame.LayoutRef.children[1].getComponent(Label).string = `${TopicManger.curScore}`
    overGame.LayoutRef.children[2].getComponent(Label).string = `最佳得分：${maxScore}`
  }

  shareRefShow() {
    console.log('分享模块')
    this.resetRef()
    this.shareRef.active = true
    overGame.isRevive = true
  }

  afreshBoxRefShow() {
    console.log('重新开始')
    this.resetRef()
    this.afreshBoxRef.active = true
  }

  videoBoxRefShow() {
    console.log('视频')
    this.resetRef()
    this.videoBoxRef.active = true
    overGame.isRevive = true
  }

  continueBoxRefShow() {
    console.log('继续游戏')
    this.resetRef()
    this.continueBoxRef.active = true
  }


  // 重置ref
  resetRef() {
    this.shareRef.active = false
    this.afreshBoxRef.active = false
    this.videoBoxRef.active = false
    this.continueBoxRef.active = false
  }

  handleShare() { // 分享
    console.log('点击分享')
    // onShareAppMessage('button')
    wx.shareAppMessage({
      title: '转发标题'
    })
    api.game.dailyShare(0).then((res) => {
      TopicManger.isShare = true
      // overGame.isRevive = true
      // this.resetRef()
      // this.continueBoxRefShow()
    })
  }
  watchVideo() { // 看视频
    console.log('看视频')
    if (this.videoAd) {
      this.videoAd.show().catch(() => {
        // 失败重试
        this.videoAd
          .load()
          .then(() => this.videoAd.show())
          .catch((err) => {
            // isShowReplay.value = true
            this.afreshBoxRefShow()
            console.log('激励视频 广告显示失败')
          })
      })
    }
  }
  restart() { // 重新开始
    console.log('重新开始11111')
    this.hideDialog()
    TopicManger.prototype.readyGo()
  }
  continueGame() { // 继续游戏
    console.log('继续游戏')
    this.hideDialog()
    TopicManger.prototype.startGame()
  }
  handleSkip() { // 跳过
    console.log('跳过')
    this.afreshBoxRefShow()
  }
  afreshShare() {
    console.log('重新开始分享BTN')
    api.game.dailyShare(0).then((res) => {
      TopicManger.isShare = true
      overGame.isRevive = true
      this.resetRef()
      this.continueBoxRefShow()
    })
  }
  backHome() {
    console.log('返回首页')
    director.loadScene('home')
  }

  hideDialog() {
    UIManager.hideDialog(Constants.UIPage.overModalDialog);
  }

  // 生成视频 
  createVideoAd() {
    try {
      if (wx.createRewardedVideoAd) {
        this.videoAd = wx.createRewardedthis.VideoAd({
          adUnitId: 'adunit-21f82624f78893e9'
        })
        this.videoAd.onLoad(() => {
          overGame.isAdEnded = true
        })
        this.videoAd.onError((err) => {
          overGame.isAdEnded = false
        })
        this.videoAd.onClose((res) => {
          if (res && res.isEnded) {
            console.log('正常播放结束，可以下发游戏奖励')
            overGame.isRevive = true
            this.resetRef()
            this.continueBoxRefShow()
            // userStore.setReviveNum(1)
          } else {
            console.log('播放中途退出，不下发游戏奖励')
          }
        })
      }
    } catch (error) {
      console.log('不在wx环境')
    }
  }
}

